package cn.tedu._05mvcboot03.comment.exception;

import cn.tedu._05mvcboot03.comment.response.JsonResult;
import cn.tedu._05mvcboot03.comment.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandlen {
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        String message = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException",message );
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex) {
        log.error("ConstraintViolationException",ex.getMessage().split(":")[1].trim());
        return new JsonResult(StatusCode.VALIDATED_ERROR,ex.getMessage().split(":")[1].trim());
    }

    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex){
        String message = ex.getMessage();
        log.error("doHandleThrowable: " + message);
        return new JsonResult(9999, "未知异常", message);
    }
}
